package controllers.rpcgame;

import java.util.ArrayList;

import dbaccessors.DBAccessor;

import asyncsenders.RPCSender;

public class RPCController {
	
	private ArrayList<RPCGameInstance> games;
	private RPCSender rpcSender;
	private static RPCController instance = null;

	private RPCController() {
		this.games = new ArrayList<RPCGameInstance>();
		this.rpcSender = new RPCSender();
	}

	public static RPCController getInstance() {
		if (instance == null) {
			instance = new RPCController();
		}
		return instance;
	}
	
	public boolean addGame(String user1, String user2, int cardID1, int cardID2){
		RPCGameInstance newGame = new RPCGameInstance(user1, user2, cardID1, cardID2);
		return this.games.add(newGame);
	}

	public String makeTurn(String username, String turn) {
		RPCGameInstance game = this.findGame(username);
		game.makeTurn(username, turn);
		
		//when both player made turn
		if (game.turnFinished()){
			String winner = game.getTurnWinner();
			if (!game.isFinished()){
				this.rpcSender.pushOpponentMove(game.getUser1(), winner, game.getOpponentTurn(game.getUser1()));
				this.rpcSender.pushOpponentMove(game.getUser2(), winner, game.getOpponentTurn(game.getUser2()));
				game.initForNextTurn();
			}			
		}
		
		//when game is finished
		if (game.isFinished()){
			String winner = game.getWinner();
			String looser = game.getLooser();
			int winnerCardID = game.getPlayerCard(winner);
			int looserCardID = game.getPlayerCard(looser);
			
			//update DB
			if (!winner.isEmpty()) //if no tie, switch cards
				DBAccessor.getInstance().fromLooserToWinner(winner, looser, winnerCardID, looserCardID);
			
			//remove game invite from DB
			DBAccessor.getInstance().removeGameInvite(game.getUser1(), game.getUser2(), game.getCardID1(), game.getCardID2());
			
			//notify the users
			this.rpcSender.pushGameFinished(game.getUser1(), winner, game.getOpponentTurn(game.getUser1()));
			this.rpcSender.pushGameFinished(game.getUser2(), winner, game.getOpponentTurn(game.getUser2()));
			
			//remove the game from arrayList
			this.games.remove(game);				
		}
		
		return turn;
	}
	
	private RPCGameInstance findGame(String username){
		for (RPCGameInstance game : games){
			if (game.getUser1().equals(username) || game.getUser2().equals(username))
				return game;
		}
		return null;
	}

}
